package com.xxkj.orcfx.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {
    /**
     * 解析 Html  的title
     *
     * @param html
     * @return
     */
    public static String extractTitle(String html) {
        String title = "";
        // 定义正则表达式匹配<title>标签内容
        Pattern pattern = Pattern.compile("<title>(.*?)</title>", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(html);
        if (matcher.find()) {
            title = matcher.group(1);
        }
        return title;

    }

    public static String getNum() {
        char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        StringBuilder nums = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 32; i++) {
            int id = random.nextInt(chars.length);
            nums.append(chars[id]);
        }
        return nums.toString();
    }


    public static String getCaptchaCode(File file) {
        // 创建HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建HttpPost请求
        HttpPost uploadFile = new HttpPost("http://upload.chaojiying.net/Upload/Processing.php");
        // 创建文件对象
        FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);

        // 构建多部分请求实体
        HttpEntity multipart = MultipartEntityBuilder.create().addPart("userfile", fileBody).addPart("user", new StringBody("pykeji", ContentType.TEXT_PLAIN)).addPart("pass2", new StringBody("1C00AD295D64CAA7AF0850E440C8277E", ContentType.TEXT_PLAIN)).addPart("softid", new StringBody("edbade6748823f3097c64a52f19bc051", ContentType.TEXT_PLAIN)).addPart("codetype", new StringBody("1902", ContentType.TEXT_PLAIN)).build();

        // 设置请求实体
        uploadFile.setEntity(multipart);

        try (CloseableHttpResponse response = httpClient.execute(uploadFile)) {
            // 获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String responseString = EntityUtils.toString(responseEntity);
                System.out.println("识别验证码返回: " + responseString);
                JSONObject resultRsp = JSONObject.parseObject(responseString);
                Integer errorCode = resultRsp.getInteger("err_no");
                String pic_str = resultRsp.getString("pic_str");
                if (errorCode == 0) {
                    return pic_str;
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }


    /**
     * 解析结果
     *
     * @param jsonTxt json
     * @return
     */
    public static String getRspResult(String jsonTxt) {
        if (StringUtils.isBlank(jsonTxt)) {
            return "";
        }
        JSONArray jsonArray = JSONArray.parseArray(jsonTxt);
        JSONObject jsonObject = (JSONObject) jsonArray.get(0);
        if (jsonObject.containsKey("result")) {
            JSONArray resultArray = jsonObject.getJSONArray("result");
            List<String> resultList = new ArrayList<>();
            for (Iterator iterator = resultArray.iterator(); iterator.hasNext(); ) {
                JSONObject obj = (JSONObject) iterator.next();
                String caseCode = obj.getString("caseCode");
                resultList.add(caseCode);
            }
            return StringUtils.join(resultList, ",");
        } else {
            return "";
        }
    }
}
